package com.group.project.hrms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.group.project.hrms.entity.OvertimeRules;
import com.group.project.hrms.entity.RestTimeSettings;
import com.group.project.hrms.entity.ResultEntity.ResultEntity;
import com.group.project.hrms.service.IOvertimeRulesService;
import com.group.project.hrms.service.IRestTimeSettingsService;
import com.group.project.hrms.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class OvertimeRulesController {

    @Autowired
    private IOvertimeRulesService iOvertimeRulesService;

    @Autowired
    private IRestTimeSettingsService iRestTimeSettingsService;

    @Autowired
    private VerificationUtil verificationUtil;

    @Autowired
    private BasicInfoUtil basicInfoUtil;

    @Autowired
    private LogUtil logUtil;

    /**
     * 该方法将获取所有加班规则并返回给前端页面
     * @param request http请求
     * @return 标准返回值对象
     */
    @RequestMapping("/basic/getAllOvertimeRules")
    @ResponseBody
    public ResultEntity getAllOvertimeRules(HttpServletRequest request){
        ResultEntity resultEntity = new ResultEntity();
        try{
            resultEntity.setCode("S");
            resultEntity.setMsg("Success");
            resultEntity.setDataList(iOvertimeRulesService.selectAllOvertimeRules());
        }catch (Exception e){
            resultEntity.setCode("F");
            resultEntity.setMsg("请求数据库失败");
        }
        return resultEntity;
    }

    /**
     * 该方法接收前端传入的创建参数，向数据库插入加班规则对象
     * @param map 创建加班规则对象数据
     * @param request http请求
     * @return 标准返回值对象
     */
    @RequestMapping("/basic/insertOvertimeRules")
    @ResponseBody
    public ResultEntity insertOvertimeRules(@RequestBody Map map, HttpServletRequest request){
        ResultEntity resultEntity = new ResultEntity();
        Object staffName = request.getAttribute("staffName");
        Date date = new Date(); //获取当前日期
        Object ruleName = map.get("ruleName"); //规则名称，10字以内
        Object minOvertimeHours = map.get("minOvertimeHours"); //最小加班时间，单位为分钟
        Object maxOvertimeHours = map.get("maxOvertimeHours"); //最大加班时间，单位为分钟
        Object overtimeUnit = map.get("overtimeUnit"); //加班步进值，单位为分钟
        Object isAllowOption = map.get("isAllowOption"); //加班记薪日选择项[1, 2, 3][工作日,周末,节假日]
        Object isMustApprove = map.get("isMustApprove"); //加班是否需要审批, [0:是, 1:否]
        Object systemTicketCode = map.get("systemTicketCode"); //关联的系统审批单据的PROC
        Object roundingMethod = map.get("roundingMethod"); //取整方式 [1:向下取整 2:向上取整]
        Object restList = map.get("restList"); //休息时段 restList=[{ timezones=[2022-04-10T17: 00: 00.714Z, 2022-04-10T18: 00: 00.646Z] }]
        if(null != ruleName && null != minOvertimeHours && null != maxOvertimeHours && null != overtimeUnit && null != isAllowOption && null != isMustApprove && null != systemTicketCode && null != roundingMethod){
            try{
                OvertimeRules targetRules = new OvertimeRules();
                List<String> restListIds = new ArrayList<>(); //用于存储休息时间段的表单IDs
                if(null != restList){
                    JSONArray restListArray = JSON.parseArray(JSON.toJSONString(restList));
                    if(restListArray.size() != 0){
                        restListIds = basicInfoUtil.doInsertRestTimeSettings(restListArray, restListIds).get("ids");
                    }
                }
                targetRules.setcTime(date);
                targetRules.setRulesId(UUIDUtil.createUUID());
                targetRules.setRulesName(ruleName.toString());
                targetRules.setMinOvertimeHours(Integer.valueOf(minOvertimeHours.toString()));
                targetRules.setMaxOvertimeHours(Integer.valueOf(maxOvertimeHours.toString()));
                targetRules.setOvertimeUnit(Integer.valueOf(overtimeUnit.toString()));
                targetRules.setRestTimeIds(JSON.toJSONString(restListIds));
                targetRules.setIsAllowWorkingDay(isAllowOption.toString().contains("1") ? 0 : 1); //1表示不允许，0表示允许
                targetRules.setIsAllowWeekend(isAllowOption.toString().contains("2") ? 0 : 1); //1表示不允许，0表示允许
                targetRules.setIsAllowHoliday(isAllowOption.toString().contains("3") ? 0 : 1); //1表示不允许，0表示允许
                targetRules.setIsMustApprove(Integer.valueOf(isMustApprove.toString()));
                targetRules.setDingProcessCode(systemTicketCode.toString());
                targetRules.setRoundingMethod(Integer.valueOf(roundingMethod.toString()));
                int i = iOvertimeRulesService.insertOvertimeRules(targetRules);
                if(i != 0){
                    logUtil.insertSystemEventLog(staffName.toString(), date, "创建了一条加班规则:" + ruleName, "考勤");
                    resultEntity.setCode("S");
                    resultEntity.setMsg("创建成功");
                    return resultEntity;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        resultEntity.setCode("F");
        resultEntity.setMsg("创建失败");
        return resultEntity;
    }

    /**
     * 该方法将接收前端删除请求，向数据库删除指定ID的加班规则
     * @param map 前端传入的数据对象
     * @param request http请求
     * @return 标准返回值对象
     */
    @RequestMapping("/basic/deleteOvertimeRules")
    @ResponseBody
    public ResultEntity deleteOvertimeRules(@RequestBody Map map, HttpServletRequest request){
        ResultEntity resultEntity = new ResultEntity();
        Object ruleId = map.get("rulesId");
        Object staffName = request.getAttribute("staffName");
        if(null != ruleId){

            //需要先校验关联性再删除
            if(!verificationUtil.confirmDeleteOverTimeRule(ruleId.toString())){
                resultEntity.setCode("F");
                resultEntity.setMsg("删除失败，该加班规则正在使用中");
            }

            OvertimeRules overtimeRules = iOvertimeRulesService.selectOneOvertimeRulesByRuleId(ruleId.toString());
            String restTimeIds = overtimeRules.getRestTimeIds();
            if(!restTimeIds.isEmpty()){
                JSONArray rids = JSON.parseArray(restTimeIds);
                for (Object id : rids
                     ) {
                    RestTimeSettings restTimeSettings = iRestTimeSettingsService.selectOneRestTimeSettingsByRestTimeId(id.toString());
                    iRestTimeSettingsService.deleteRestTimeSettings(restTimeSettings);
                }
            }
            int i = iOvertimeRulesService.deleteOvertimeRules(overtimeRules);
            if(i != 0){
                logUtil.insertSystemEventLog(staffName.toString(), new Date(), "删除了一条加班规则:" + overtimeRules.getRulesName(), "考勤");
                resultEntity.setCode("S");
                resultEntity.setMsg("删除成功");
            }else{
                resultEntity.setCode("F");
                resultEntity.setMsg("删除失败");
            }
        }else{
            resultEntity.setCode("F");
            resultEntity.setMsg("删除失败");
        }
        return resultEntity;
    }

    /**
     * 暂时不提供这个功能
     * @param map
     * @param request
     * @return
     */
    @RequestMapping("/basic/updateOvertimeRules")
    @ResponseBody
    public ResultEntity updateOvertimeRules(@RequestBody Map map, HttpServletRequest request){
        ResultEntity resultEntity = new ResultEntity();
        Date date = new Date(); //获取当前日期
        Object rulesId = map.get("rulesId");
        if(null != rulesId){
            OvertimeRules orgObject = iOvertimeRulesService.selectOneOvertimeRulesByRuleId(rulesId.toString());
            System.out.println(map);
        }
        return resultEntity;
    }

}
